/*
 *  textscreen.c
 *  xD-OS
 *
 *  Created by James Johns on 22/07/2009.
 *  Copyright 2009 xD-Dunce. All rights reserved.
 *
 */

#include "global.h"
#include "textscreen.h"
#include "stdio.h"


void initScreen(){
	screen = (Byte *)0xb8000;
	attributes = ((BLACK << 4) | (WHITE & 0x0F));
	clearScreen();
	updateCursor();
}


void clearScreen(){
	int i;
	for(i = 0; i<(80*2*23); i += 2){
		screen[i] = 0x20;
		screen[i+1] = attributes;
	}
	cursorX = cursorY = 0;
}


void updateCursor(){
	Word pos = cursorY *80 +cursorX;
	
	outB(0x3D4, 14);
	outB(0x3D5, pos>>8);
	outB(0x3D4, 15);
	outB(0x3D5, pos);
}

void printChar(Byte c){
	if(c == '\n'){
		newLine();
	}
	else{
		Word pos = (cursorY *80 +cursorX)*2;
		screen[pos] = c;
		screen[pos+1] = attributes;
		cursorX++;
	}
	if(cursorX > 80){
		cursorX = 0;
		cursorY++;
	}
	if(cursorY > 23){
		scroll();
	}
}

void printString(Byte *string){
	int i;
	dWord length = strlen(string);
	for(i = 0; i<length; i++){
		printChar(string[i]);
	}
	updateCursor();
}

void printHex(dWord n){
	signed int tmp;
	
	printString("0x");
	
    char noZeroes = 1;
	
    int i;
    for (i = 28; i > 0; i -= 4)
    {
        tmp = (n >> i) & 0xF;
        if (tmp == 0 && noZeroes != 0)
        {
            continue;
        }
		
        if (tmp >= 0xA)
        {
            noZeroes = 0;
            printChar (tmp-0xA+'a' );
        }
        else
        {
            noZeroes = 0;
            printChar( tmp+'0' );
        }
    }
	
    tmp = n & 0xF;
    if (tmp >= 0xA)
    {
        printChar (tmp-0xA+'a');
    }
    else
    {
		printChar(tmp+'0');
    }
}

void printInt(dWord n){

	if (n == 0)
    {
        printChar('0');
        return;
    }
	
    signed int acc = n;
    char c[32];
    int i = 0;
    while (acc > 0)
    {
        c[i] = '0' + acc%10;
        acc /= 10;
        i++;
    }
    c[i] = 0;
	
    char c2[32];
    c2[i--] = 0;
    int j = 0;
    while(i >= 0)
    {
        c2[i--] = c[j++];
    }
    printString(c2);
}

void newLine(){
	cursorX = 0;
	cursorY++;
	if(cursorY > 23){
		scroll();
	}
}

void scroll(){
	int i;
	for(i = 0; i < 23*80*2; i++){
		screen[i] = screen[i+160];
	}
	for(i = 23*80*2; i < 24*80*2; i++){
		screen[i++] = 0x20;
		screen[i] = attributes;
	}
	cursorY = 23;
	cursorX = 0;
}
